package cn.iocoder.yudao.module.currency.service.rate;

import cn.iocoder.yudao.module.currency.config.PaymentCurrencyConfig;
import cn.iocoder.yudao.module.currency.dal.dataobject.rate.ExchangeRateDO;
import cn.iocoder.yudao.module.currency.dal.mysql.rate.ExchangeRateMapper;
import cn.iocoder.yudao.module.currency.util.ExchangeRateThirdDTO;
import cn.iocoder.yudao.module.currency.util.ExchangeRateUtils;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class ExchangeRateSyncService {

    @Resource
    private PaymentCurrencyConfig paymentCurrencyConfig;

    @Resource
    private DictDataApi dictDataApi;

    @Resource
    private ExchangeRateService exchangeRateService;

    @Resource
    private ExchangeRateMapper exchangeRateMapper;

    public int syncAllRate() {
        int count = 0;
        if (!paymentCurrencyConfig.getSyncEnable()) {
            log.info("同步货币汇率, 未开启, 如需开启, 请检查配置: payment.currency.sync-enable");
            return count;
        }
        // 获取所有货币
        String dictKey = paymentCurrencyConfig.getDictKey();
        if (StringUtils.isBlank(dictKey)) {
            log.info("同步货币汇率, 未配置字典key, 请检查配置: payment.currency.dict-key");
            return count;
        }
        List<DictDataRespDTO> dictDataList = dictDataApi.getDictDataList(dictKey);
        for (DictDataRespDTO dict : dictDataList) {
            String label = dict.getLabel();
            String value = dict.getValue();
            if (StringUtils.isBlank(label) || StringUtils.isBlank(value)) {
                continue;
            }
            String[] split = label.split("/");
            if (split.length != 2) {
                log.info("同步货币汇率, 货币: {} 格式错误, 请参考: USD/CNY", label);
                continue;
            }
            String baseCurrency = split[0];
            String targetCurrency = split[1];
            if (StringUtils.isBlank(baseCurrency) || StringUtils.isBlank(targetCurrency)) {
                log.info("同步货币汇率, 货币: {} 格式错误, 请参考: USD/CNY", label);
                continue;
            }
            BigDecimal baseRate = new BigDecimal(value);
            // 获取货币的汇率
            ExchangeRateThirdDTO exchangeThird = ExchangeRateUtils.fetchCurrencyExchange(baseCurrency, targetCurrency);
            if (Objects.nonNull(exchangeThird)) {
                BigDecimal exchangeThirdPrice = exchangeThird.getPrice();
                BigDecimal finalRate = baseRate;
                if (exchangeThirdPrice.compareTo(baseRate) < 0) {
                    log.info("第三方汇率小于保底汇率, 货币: {}, 第三方汇率: {}, 保底汇率: {}. 更新为第三方汇率", label, exchangeThirdPrice, baseRate);
                    finalRate = exchangeThirdPrice;
                } else {
                    log.info("第三方汇率大于保底汇率, 货币: {}, 第三方汇率: {}, 保底汇率: {}. 更新为保底汇率", label, exchangeThirdPrice, baseRate);
                }
                // 更新所有货币的汇率
                ExchangeRateDO exchangeRate = exchangeRateService.getExchangeRate(baseCurrency, targetCurrency);
                if (Objects.nonNull(exchangeRate)) {
                    int result = exchangeRateMapper.updateById(
                            ExchangeRateDO.builder()
                                    .id(exchangeRate.getId())
                                    .exchangeRate(finalRate)
                                    .build()
                    );
                    if (result > 0) {
                        log.info("同步货币汇率, 货币: {}, 汇率更新成功", label);
                        count++;
                    }
                } else {
                    log.info("同步货币汇率, 货币: {}, 汇率未配置", label);
                }
            } else {
                log.info("同步货币汇率, 货币: {}, 获取汇率失败", label);
            }
        }

        return count;
    }
}
